from peewee import (
    MySQLDatabase, Model, IntegerField, DateTimeField, AutoField, SQL,
)
from application.settings import MYSQL_DATABASES


class BaseMysqlModel(Model):
    list_id = AutoField()  # 自增主键
    is_del = IntegerField(constraints=[SQL("DEFAULT 0")])  # 是否删除：0-否，1-是
    update_time = DateTimeField(null=True)  # 更新时间
    create_time = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")])  # 创建时间

    class Meta:
        database = None  # 将在子类中设置具体的数据库连接

    @classmethod
    def set_database(cls, db_config_key='default'):
        """
        设置模型使用的数据库
        
        Args:
            db_config_key (str): 数据库配置键名，默认为'default'
        """
        if db_config_key in MYSQL_DATABASES:
            data_base = MYSQL_DATABASES[db_config_key]
            cls._meta.database = MySQLDatabase(
                data_base['database'],  # 数据库名称
                user=data_base['user'],  # 用户名
                password=data_base['password'],  # 密码
                host=data_base['host'],  # 主机地址
                port=data_base['port']  # 端口
            )

        else:
            raise ValueError(f"Database configuration '{db_config_key}' not found in MYSQL_DATABASES")
